<template>
  <div class="menu-container">
    <div class="error-msg" v-if="errorMsg">{{ errorMsg }}</div>
    <el-menu class="menu" :default-active="activeIndex" @select="handleSelect">
      <el-sub-menu
          class="el-sub-menu"
          v-for="(menu, index) in menuList"
          :key="index"
          :index="index.toString()"
      >
        <template #title>
          <span>{{ menu.title }}</span>
        </template>
        <el-menu-item
            v-for="(child, childIndex) in menu.children"
            :key="childIndex"
            :index="child.path"
        >
          <router-link :to="child.path" class="menu-link">
            {{ child.title }}
          </router-link>
        </el-menu-item>
      </el-sub-menu>
    </el-menu>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, toRefs } from "vue";
import http from "@/axios/http";
import qs from "qs";
import { dynamicAddRoute } from "@/util/dynamicRoute";
import { useUserStore } from "@/store/userStore.js";
import router from "@/util/router.js";

let errorMsg = ref("");
const menuList = ref([]);
const activeIndex = ref("/");

const props = defineProps({
  roleid: Number,
});

const { roleid } = toRefs(props);

onMounted(() => {
  init();
});

function init() {
  let userStore = useUserStore();
  console.log("user");
  console.log(userStore.getUserinfo);
  const param = reactive({
    roleid: userStore.getUserrole,
  });
  // 查询菜单
  http.post("/lyy/getmenus", qs.stringify(param)).then((res) => {
    let resultmenu = res.data;

    if (resultmenu.result === "success") {
      menuList.value = resultmenu.data;
      console.log(menuList);
      dynamicAddRoute(menuList.value);
      if (menuList.value === null) {
        errorMsg.value = "获取菜单失败！";
      }
    } else {
      console.log(resultmenu.error);
      errorMsg.value = "获取菜单失败！";
      // router.push({ path: '/login' });
    }
  });
}

function handleSelect(index) {
  activeIndex.value = index;
}
</script>

<style scoped>
.menu-container {
  background-color: #f5f5f5;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.error-msg {
  color: red;
  font-style: italic;
  margin-bottom: 20px;
  animation: fadeIn 0.5s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.menu {
  background-color: #ffffff;
  border-radius: 5px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.el-sub-menu {
  border-bottom: 1px solid #f0f0f0;
}

.el-sub-menu > .el-menu-item {
  padding: 0 20px;
}

.menu-link {
  text-decoration: none;
  color: #333;
  display: block;
  padding: 10px 20px;
  transition: background-color 0.3s ease;
}

.menu-link:hover {
  background-color: #f0f0f0;
}

.menu-link.router-link-active {
  background-color: #e6f7ff;
  color: #1890ff;
}
</style>